package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import com.sky.constant.MessageConstant;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 * @author ACE-Felix
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        // Duplicate entry 'ace' for key 'employee.idx_username'
        log.error("异常信息：{}", ex.getMessage());
        // 获取异常信息
        String msg = ex.getMessage();
        // 判断异常信息中是否包含Duplicate entry
        if (msg.contains("Duplicate entry")) {
            // 以空格分割异常信息
            String[] split = msg.split(" ");
            // 获取用户名
            // String username = split[2];
            String username = split[2].substring(1, split[2].length() - 1);
            return Result.error("用户名【" + username + "】" + MessageConstant.ALREADY_EXISTS);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

}
